package initialize

import (
	"context"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemService "github.com/flipped-aurora/gin-vue-admin/server/service/system"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// Dictionary 初始化字典数据
func Dictionary(ctx context.Context) {
	if err := initSysTaskDictionaries(ctx); err != nil {
		zap.L().Error(fmt.Sprintf("初始化字典失败: %+v", err))
	}
}

// initSysTaskDictionaries 初始化 sysTask 相关字典
func initSysTaskDictionaries(ctx context.Context) error {
	// 初始化字典
	dictionaries := []system.SysDictionary{
		{
			Name:   "定时任务状态",
			Type:   "sysTaskStatus",
			Status: getBoolPtr(true),
			Desc:   "定时任务状态",
		},
		{
			Name:   "定时任务类型",
			Type:   "sysTaskType",
			Status: getBoolPtr(true),
			Desc:   "定时任务类型",
		},
	}

	// 创建字典
	for _, dict := range dictionaries {
		if err := createDictionaryIfNotExists(dict); err != nil {
			return errors.Wrap(err, fmt.Sprintf("创建字典 %s 失败", dict.Name))
		}
	}

	// 初始化字典详情
	if err := initSysTaskStatusDetails(); err != nil {
		return errors.Wrap(err, "初始化任务状态字典详情失败")
	}

	if err := initSysTaskTypeDetails(); err != nil {
		return errors.Wrap(err, "初始化任务类型字典详情失败")
	}

	return nil
}

// createDictionaryIfNotExists 如果字典不存在则创建
func createDictionaryIfNotExists(dict system.SysDictionary) error {
	var existingDict system.SysDictionary
	err := global.GVA_DB.Where("type = ?", dict.Type).First(&existingDict).Error
	
	if errors.Is(err, gorm.ErrRecordNotFound) {
		// 字典不存在，创建新字典
		return systemService.DictionaryServiceApp.CreateSysDictionary(dict)
	} else if err != nil {
		// 其他错误
		return err
	}
	
	// 字典已存在，不需要创建
	return nil
}

// initSysTaskStatusDetails 初始化任务状态字典详情
func initSysTaskStatusDetails() error {
	// 获取字典ID
	var dict system.SysDictionary
	if err := global.GVA_DB.Where("type = ?", "sysTaskStatus").First(&dict).Error; err != nil {
		return err
	}

	details := []system.SysDictionaryDetail{
		{Label: "Disabled", Value: "99", Status: getBoolPtr(true), Sort: 1, SysDictionaryID: int(dict.ID)},
		{Label: "Failure", Value: "0", Status: getBoolPtr(true), Sort: 2, SysDictionaryID: int(dict.ID)},
		{Label: "Enabled", Value: "1", Status: getBoolPtr(true), Sort: 3, SysDictionaryID: int(dict.ID)},
		{Label: "Running", Value: "10", Status: getBoolPtr(true), Sort: 4, SysDictionaryID: int(dict.ID)},
		{Label: "Finish", Value: "2", Status: getBoolPtr(true), Sort: 5, SysDictionaryID: int(dict.ID)},
		{Label: "Cancel", Value: "3", Status: getBoolPtr(true), Sort: 6, SysDictionaryID: int(dict.ID)},
	}

	return createDictionaryDetailsIfNotExists(details)
}

// initSysTaskTypeDetails 初始化任务类型字典详情
func initSysTaskTypeDetails() error {
	// 获取字典ID
	var dict system.SysDictionary
	if err := global.GVA_DB.Where("type = ?", "sysTaskType").First(&dict).Error; err != nil {
		return err
	}

	details := []system.SysDictionaryDetail{
		{Label: "httpTask", Value: "httpTask", Status: getBoolPtr(true), Sort: 1, SysDictionaryID: int(dict.ID)},
		{Label: "internalFuncTask", Value: "internalFuncTask", Status: getBoolPtr(true), Sort: 2, SysDictionaryID: int(dict.ID)},
		{Label: "shellTask", Value: "shellTask", Status: getBoolPtr(true), Sort: 3, SysDictionaryID: int(dict.ID)},
	}

	return createDictionaryDetailsIfNotExists(details)
}

// createDictionaryDetailsIfNotExists 如果字典详情不存在则创建
func createDictionaryDetailsIfNotExists(details []system.SysDictionaryDetail) error {
	for _, detail := range details {
		var existingDetail system.SysDictionaryDetail
		err := global.GVA_DB.Where("sys_dictionary_id = ? AND value = ?", detail.SysDictionaryID, detail.Value).First(&existingDetail).Error
		
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 详情不存在，创建新详情
			if err := systemService.DictionaryDetailServiceApp.CreateSysDictionaryDetail(detail); err != nil {
				return err
			}
		} else if err != nil {
			// 其他错误
			return err
		}
		// 详情已存在，跳过
	}
	return nil
}

// getBoolPtr 获取布尔值指针
func getBoolPtr(b bool) *bool {
	return &b
}